<template>
  <div class="container-right-chat" ref="chatListRef">
    <div style="display: flex; justify-content: flex-end">
      <el-dropdown>
        <el-icon style="font-size: 30px; color: var(--el-color-primary); float: right"><UploadFilled /></el-icon>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>下载为doc</el-dropdown-item>
            <el-dropdown-item>下载为pdf</el-dropdown-item>
            <el-dropdown-item>下载为txt</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="container-right-chat-item" v-for="(item, index) in state.chatList" :key="index">
      <div class="container-right-chat-item-icon">
        <SvgIcon style="font-size: 28px" :name="item.issuer == 1 ? 'user' : 'jqr'" />
      </div>
      <div class="container-right-chat-item-content" style="width: 100%">
        <div class="container-right-chat-item-content-title">{{ item.issuer == 1 ? "你：" : "机器人：" }}</div>
        <div class="container-right-chat-item-content-label" v-if="item.issuer == 1">
          {{ item.message }}
        </div>
        <div class="container-right-chat-item-content-label2" v-if="item.issuer == 2">
          <div style="width: 100%" v-if="item.isNew">
            <TypeWriter style="background-color: transparent; margin: 10px" :text="item.message" height="100%" />
          </div>
          <div class="container-right-chat-item-content-label" v-else>
            {{ item.message }}
          </div>
          <div
            v-if="item.sources && item.sources.length > 0"
            @click="item.isMore = !item.isMore"
            class="container-right-chat-item-content-label2-from"
          >
            <span>情报资料出处</span>
            <el-icon style="margin-left: 4px"><ArrowDown /></el-icon>
          </div>
          <div style="clear: both" />
          <div class="container-right-chat-item-content-label2" style="background-color: #fff" v-if="item.isMore">
            <el-collapse accordion>
              <el-collapse-item :name="i" v-for="(e, i) in item.sources" :key="i">
                <template #title>
                  <div>{{ e.content }}</div>
                </template>
                <el-link
                  style="white-space: nowrap; margin-top: 10px"
                  @click="handleDownLoad(e.attr.href, e.content)"
                  type="primary"
                >
                  路径：{{ e.attr.path }}</el-link
                >
                <div style="text-align: right">
                  <el-link @click="handleDialog(e.attr.href)" style="margin-top: 13px" type="primary">查看原文</el-link>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="_t.dialog_conf.visiable"
      :title="_t.dialog_conf.title"
      :destroy-on-close="_t.dialog_conf.isDestory"
      :draggable="_t.dialog_conf.draggable"
      :close-on-click-modal="_t.dialog_conf.closeOnClickModal"
      width="1100px"
    >
      <iframe :src="_t.cur_wps_href" width="100%" height="600px" style="border: none" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import TypeWriter from "@/components/TypeWriter/index.vue"
import { reactive, nextTick, ref, defineProps, onMounted, defineExpose } from "vue"
import { useUserStore } from "@/store/modules/user"
import Bus from "@/utils/bus"
import { getTags, exportFile } from "@/utils/index"
import { getResult } from "@/api/large-model/index"
import { createChat, findChat } from "@/api/chat/index"
const _props = defineProps({ sessionId: String })
const chatListRef = ref(null)
const _t = reactive({
  cur_chat_list: [],
  dialog_conf: {
    visiable: false,
    title: "原文",
    isDestory: false, //关闭前销毁
    draggable: true, //拖拽
    closeOnClickModal: false
  },
  cur_wps_href: ""
})

const state = reactive({
  chatList: []
})

const handleDialog = (v: string) => {
  _t.cur_wps_href = `https://docs.google.com/gview?url=${decodeURIComponent(v)}&embedded=true`
  _t.dialog_conf.visiable = true
}
const userStore = useUserStore()
const getString = (url: string) => {
  const start = url.indexOf(".com")
  const end = url.indexOf("?")
  if (start === -1 || end === -1 || start >= end) {
    return "" // 没有找到或者位置不正确时返回空字符串
  }
  return url.substring(start + 4, end)
}

const handleDownLoad = (path: string, name: string) => {
  exportFile(path, name, true, true)
}

Bus.on("enter-text", (v) => {
  const time = Date.now()
  state.chatList.push({
    issuer: 1, // 1、用户 2、机器人
    message: v,
    time: time,
    sessionId: _props.sessionId
  })
  state.chatList.push({
    issuer: 2, // 1、用户 2、机器人
    isMore: false,
    time: time,
    message: "。。。。。。",
    sessionId: _props.sessionId,
    sources: [],
    isNew: true
  })
  getResult({
    Prompt: v,
    AppId: userStore?.userinfo?.AppId
    // sessionId: 1,
    // RequestId: requestId,
    // History: _t.cur_chat_list.filter((item) => item.issuer == 1).map((item) => ({
    //   text:
    // }))
  }).then((res: any) => {
    if (res.code == 200) {
      const text = res?.data?.Data?.Text ?? ""
      const msg = state.chatList.filter((item: any) => item.time == time)
      msg.map((item: any) => (item.issuer == 2 ? (item.message = text.split("<sup>")?.[0] ?? "") : " 。。。。。。"))
      console.log("msg", msg)
      createChat(msg).then((response: any) => {
        if (response.code == 200) {
          getList(time)
        }
      })
      let sources = getTags(text)
      sources = sources.map((item) => {
        item.content = item.attr.title
        item.attr.path = getString(item.attr.href)
        return item
      })
      msg.map((item: any) => (item.issuer == 2 ? (item.sources = sources) : []))
    }
    // _t.cur_chat_list[_t.cur_chat_list.length - 1].sessionId = res?.data?.Data?.SessionId
    // _t.cur_chat_list[_t.cur_chat_list.length - 1].requestId = res?.data?.RequestId
  })
})

const getList = (time: number) => {
  findChat(_props.sessionId)
    .then((res: any) => {
      if (res.code == 200) {
        state.chatList = res.data
        nextTick(() => {
          chatListRef.value!.scrollTop = chatListRef.value?.scrollHeight
        })
        state.chatList.map((item: any) => {
          if (item.time == time && item.issuer == 2) {
            item.isNew = true
          }
        })
      }
    })
    .catch((err: any) => {
      console.log(err)
    })
}

onMounted(() => {})
defineExpose({ getList })
</script>

<style scoped lang="scss">
@import "@/styles/mixins.scss";
.container-right-chat {
  height: 100%;
  overflow-y: scroll;
  padding: 15px 10px;
  @extend %noScrollbar;
  &-item {
    display: flex;
    width: 100%;
    margin-bottom: 15px;
    &-content {
      &-title {
        font-size: 16px;
        line-height: 28px;
        margin-left: 8px;
        font-weight: bold;
      }
      &-label {
        width: 100%;
        line-height: 24px;
        margin-top: 5px;
        padding-left: 8px;
      }

      &-label2 {
        width: 100%;
        background: rgb(240, 244, 250);
        /* padding: 10px; */
        line-height: 24px;
        color: rgb(112, 129, 164);

        &-from {
          text-align: right;
          margin: 10px 20px 20px 0;
          font-weight: bold;
          padding: 2px 15px;
          border: 1px solid rgba(112, 129, 164, 0.7);
          font-size: 12px;
          float: right;
          cursor: pointer;
          display: flex;
          align-items: center;
        }
      }
    }
  }
  /* container-right-chat-item-content-title */
}
</style>
